<!-- 刘伟负责的客户管理界面 -->
<template>
    <div class="customer-list">
        <div class="action-bar">
            <el-button type="primary" @click="addCustomerBtn">新增</el-button>
            <el-button>批量操作</el-button>
            <el-button>导入</el-button>
            <el-button>导出</el-button>
        </div>


        <div class="search-bar">
            <el-form :inline="true" :model="formInline" class="demo-form-inline">
                <el-form-item label="客户级别">
                    <el-select v-model="param.level" placeholder="请选择">
                        <el-option label="全部" value=""></el-option>
                        <el-option label="VIP" value="1"></el-option>
                        <el-option label="普通" value="0"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="创建日期">
                    <el-date-picker v-model="dateRange" type="daterange" range-separator="至" start-placeholder="开始日期"
                        end-placeholder="结束日期">
                    </el-date-picker>
                </el-form-item>
                <el-form-item>
                    <el-input v-model="param.keyword" placeholder="请输入关键词搜索"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="queryCustomerBtn">搜索</el-button>
                    <el-button @click="reset">重置</el-button>
                </el-form-item>
            </el-form>
        </div>


        <el-table :data="tableData" style="width: 100%" @selection-change="handleSelectionChange">
            <!-- 这是多选栏 -->
            <el-table-column type="selection" width="55">
            </el-table-column>

            <el-table-column prop="createdTime" label="创建时间" width="180">
                <template slot-scope="scope">
                    {{ formatDate(scope.row.createdTime) }}
                </template>
            </el-table-column>
            <el-table-column prop="id" label="客户编号" width="180"></el-table-column>
            <el-table-column prop="name" label="客户名称"></el-table-column>
            <el-table-column prop="industry" label="所属行业"></el-table-column>
            <el-table-column prop="customerStatus" label="状态">
                <template slot-scope="scope">
                    <span :class="['status-tag', scope.row.customerStatus == 1 ? 'status-enabled' : 'status-disabled']">
                        {{ scope.row.customerStatus == 1 ? '启用' : '未启用' }}
                    </span>
                </template>
            </el-table-column>
            <el-table-column prop="companyContact" label="联系人姓名">
                <template slot-scope="scope">
                    {{ scope.row.companyContact }}
                    <span v-if="scope.row.level === 1" class="crown-icon">👑</span>
                </template>
            </el-table-column>
            <el-table-column prop="contactInfo" label="手机号码"></el-table-column>
            <el-table-column label="操作" width="200">
                <!-- 用插槽技术 -->
                <template slot-scope="scope">
                    <el-button size="mini">编辑</el-button>
                    <el-button size="mini" type="danger" @click="deleteCustomer(scope.row.id)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <el-col :span="24">
            <!--
                放分页部分
                :page-size: 指定每页多少条
            -->
            <el-pagination background :page-sizes="[2, 5, 10, 20, 30, 40, 50]" :page-size="pageSize"
                :current-page="pageNum" :total="total" layout="total, sizes, prev, pager, next, jumper"
                @next-click="nextPage" @prev-click="prevPage" @current-change="changePage" @size-change="sizeChange">
            </el-pagination>
        </el-col>
    </div>
</template>

<script>
export default {
    name: 'CustomerList',
    data() {
        return {
            formInline: {},         // formInline 是 Vue 组件中的一个对象，存储用户输入的表单数据。
            pageSize: 2,
            pageNum: 1,
            total: 0,
            tableData: [],          // 展示的数据
            dateRange: [],          // dateRange 数组的第一个元素是开始日期，第二个元素是结束日期。
            param: {                // 搜索的时候用到的信息
                level: '',
                startDate: '',      // 开始时间初始化为空字符串
                endDate: '',        // 结束时间初始化为空字符串
                keyword: ''
            }
        }
    },
    watch: {
        dateRange(newVal) {
            if (newVal && newVal.length === 2) {
                this.param.startDate = this.formatDateForBackend(newVal[0]);
                this.param.endDate = this.formatDateForBackend(newVal[1]);
            } else {
                this.param.startDate = '';
                this.param.endDate = '';
            }
        }
    },
    methods: {
        formatDateForBackend(date) {
            if (!date) return '';
            return date.toISOString().split('T')[0]; // 格式化为 'YYYY-MM-DD'
        },

        // 格式化日期
        formatDate(dateString) {
            const date = new Date(dateString);
            return date.toLocaleString('zh-CN', {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit',
                hour12: false
            });
        },
        // 分页相关的方法
        nextPage(val) {     // 当前页(方法自动获取当前页)
            this.pageNum = val;
            this.queryCustomer();
        },
        prevPage(val) {     // 上一页
            this.pageNum = val;
            this.queryCustomer();
        },
        changePage(val) {
            this.pageNum = val;
            this.queryCustomer();
        },
        sizeChange(val) {
            this.pageNum = 1;
            this.pageSize = val;
            this.queryCustomer();
        },
        queryCustomerBtn() {
            // 解查询不到当前页之前的问题
            this.pageNum = 1;
            this.queryCustomer();
        },
        // 查询CustomerManagement
        queryCustomer() {
            let pageParam = {};
            // 分页参数 当前页 每页多少条
            pageParam.pageNum = this.pageNum;
            pageParam.pageSize = this.pageSize;
            // 获取业务参数
            pageParam.param = this.param;

            // 前端发送一个相对复杂的json数据
            // 1.数据结构要对上(对象{}，后端只能有对象接收，数组用集合接收)
            // 2.属性名要对上
            this.$axios.post('api/customerManagement/queryCustomer', pageParam)       // pageParam是局部变量，直接用就可以了，没必要用this修饰
                .then(resp => {
                    console.log(resp.data)
                    if (resp.data.code == 200) {
                        console.log('Received data:', resp.data.data.list);     // 打印接收到的数据 
                        // 给数据赋值
                        this.tableData = resp.data.data.list
                        // 给分页总数赋值
                        this.total = resp.data.data.total
                    }
                })
        },
        // 重置
        reset() {
            this.dateRange = [],
                this.param = {
                    level: '',
                    startDate: '',
                    endDate: '',
                    keyword: ''
                };
            this.queryCustomerBtn();
        },
        // 单删
        deleteCustomer(id) {
            this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                // 修改这里的请求路径
                this.$axios.get(`/api/customerManagement/deleteCustomer/${id}`)
                    .then(resp => {
                        console.log(resp.data)
                        if (resp.data.code == 200) {
                            this.$message({
                                type: 'success',
                                message: '删除成功!'
                            });
                            // 重新查询刷新页面数据
                            this.queryCustomerBtn();
                        }
                    })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
        // 打开新增界面
        addCustomerBtn() {
            this.addCustomer();
        },
        // 新增，路由去新的界面
        addCustomer() {
            this.$router.push({ path: '/addCustomer' });
        }

    },
    created() {
        // 进来就查一下
        // this.queryCustomerBtn();
    }
}
</script>

<style scoped>
.customer-list {
    padding: 20px;
}

.action-bar,
.search-bar {
    margin-bottom: 20px;
}

.pagination {
    margin-top: 20px;
    text-align: right;
}

.status-tag {
    padding: 2px 6px;
    border-radius: 4px;
    font-size: 12px;
}

.status-enabled {
    background-color: #67C23A;
    color: white;
}

.status-disabled {
    background-color: #FFCCCB;
    /* 淡红色 */
    color: #F56C6C;
}

.crown-icon {
    margin-left: 5px;
    font-size: 14px;
}
</style>
